package ntd.util.modular.other.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import ntd.util.UtilCatch;
import ntd.util.frame.data.factory.FactoryData;
import ntd.util.frame.javacv.ComVisionApi;
import ntd.util.frame.javacv.action.bean.VisionModelDo;

import ntd.util.frame.javacv.config.AiConfig;
import ntd.util.frame.javacv.remote.AiVisionRemote;
import ntd.util.frame.javacv.tool.ToolFtpSync;
import ntd.util.frame.storage.bo.StorageInAiFileBO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.sql.SQLException;


import java.util.List;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/public/ai-file-analysis")
public class ControllerAiFileAnalysis {
    private static int aiRemoteIndex = 0;

//    @PostMapping("/stores")
//    public List<StorageOutBO> stores(@RequestPart("files") MultipartFile[] files, @Valid StorageInAiFileBO storage) {
//        List<StorageOutBO> storageOutBOList = new ArrayList<>();
//        for (MultipartFile file : files) {
//            storageOutBOList.add(ntdStorageService.store(file, storage));
//        }
//        return storageOutBOList;
//    }

    @PostMapping("/single-file")
    public String store(@RequestPart MultipartFile file, @Valid StorageInAiFileBO storage) {
        // 按模型分组
        Db db = Db.use(FactoryData.dataSource("272ab1b9c5cc4ea2b76302238247284c"));
        List<AiVisionRemote> aiVisionRemotes = ComVisionApi.analysisRemoteList();
        try {

            List<VisionModelDo> aiVisionModelAll = db.findAll(new Entity("ai_vision_model"), VisionModelDo.class);

            //支持的模型
            for (VisionModelDo visionModelDo : aiVisionModelAll) {
                //模型匹配
                if (StrUtil.equals(storage.getModelType(), visionModelDo.getCode())) {
                    AiVisionRemote aiVisionRemote = aiVisionRemotes.get(aiRemoteIndex++ % aiVisionRemotes.size());


                        String remoteFtpPath = StrUtil.format("{}{}", AiConfig.AI_SERVER_DATA_BASE_PATH, AiConfig.AI_ONLINE_FILE_ANALYSIS);

                        ToolFtpSync toolFtpSync = aiVisionRemote.getFtpSync();
                        String imgName = StrUtil.format("{}-{}{}",IdUtil.simpleUUID(), AiConfig.AI_ONLINE_FILE_ANALYSIS,
                                Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".")));

                         UtilCatch.tryCatchNoRes(() -> toolFtpSync.upload(remoteFtpPath, imgName, file.getBytes()));


                        //记录分析到数据库
                        Entity entity = Entity.create("ai_file_analysis");
                        entity.set("file_name",imgName);
                        entity.set("file_type",storage.getFileType());
                        entity.set("model_type",storage.getModelType());
                        entity.set("create_time",DateUtil.now());

                        db.insert(entity);

                        //上传成功后 调用分析
                        aiVisionRemote.analyse(StrUtil.format("{}/{}",remoteFtpPath,imgName), visionModelDo.getCode(), visionModelDo.getPortNormal());


                    break;
                }

            }

        } catch (SQLException e) {
            StaticLog.error(e, "[AI][文件分析][{}]失败...");
        }

        Map<String,Object> map = MapUtil.newHashMap();
        map.put("code",200);
        map.put("msg","请求成功,正在分析中");
        return JSONUtil.toJsonStr(map);
    }

}
